# Copyright (C) 2005-2006 Frederic Back <fredericback@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.

import gtk
import gobject

class QueryEditor( gtk.Window ):
    """ A window to enter an sql query.
    
        In the future, a possible query builder should be hosted here,
        as a tab. """

    def __init__(self):
        gtk.Window.__init__(self)
        self.set_title("Query Editor")

        #self.connect("delete-event",self.close)

        self.notebook = gtk.Notebook()
        self.notebook.set_tab_pos(gtk.POS_BOTTOM)
        self.add(self.notebook)

        hbox = gtk.HBox()
        hbox.set_border_width(2)
        self.notebook.append_page(hbox,gtk.Label("SQL"))
        

        s = gtk.ScrolledWindow()
        s.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        s.set_shadow_type(gtk.SHADOW_IN)
        textview = gtk.TextView() 
        #textview.set_wrap_mode(gtk.WRAP_WORD)
        textview.set_editable(True)
        s.add(textview)
        s.set_size_request(300,-1)
        self.textview = textview
        
        hbox.pack_start(s)
            
        buttons = gtk.VBox()
        hbox.pack_start(buttons,False)

        self.okButton = gtk.Button(None,gtk.STOCK_EXECUTE)
        buttons.pack_start(self.okButton)

        # colour the text red on an error, remove marks when editing again.
        self.textbuffer = textview.get_buffer()
        self.textbuffer.create_tag("err", background="red")
        self.textbuffer.connect("changed", self.__onEdited)

        # show all inside the window, but not the window itself
        self.notebook.show_all()

    def close(self, widget=None, event=None):
        self.destroy()

    def present(self):
        self.textview.grab_focus()
        gtk.Window.present(self)

    def getQuery(self):
        b = self.textbuffer
        return str(b.get_text(b.get_start_iter(),b.get_end_iter()))

    def setQuery(self, query):
        self.textbuffer.set_text( str(query) )
        self.notebook.set_current_page(0)
        print query
    
    def markError(self, msg):
        """ Call this when an sql statement produced an error. """
        err = 'syntax error at or near "'
        msg = str(msg)
        p = msg.find(err)
        if p > -1:
            m = msg.splitlines()[0]
            s = m[p+len(err):m.rfind('"')]
            n = int(m[m.rfind(' '):]) - 1
            self.textbuffer.apply_tag_by_name("err",
                self.textbuffer.get_iter_at_offset(n),
                self.textbuffer.get_iter_at_offset(n+len(s)))

    def __onEdited(self, widget):
        # remove tags
        widget.remove_all_tags(widget.get_start_iter(),widget.get_end_iter())
